<?php defined('BASEPATH') || exit('No direct script access allowed');

/**
 * Tgsz controller
 */
class Tgsz extends Admin_Controller
{
    protected $permissionCreate = 'Phone.Tgsz.Create';
    protected $permissionDelete = 'Phone.Tgsz.Delete';
    protected $permissionEdit   = 'Phone.Tgsz.Edit';
    protected $permissionView   = 'Phone.Tgsz.View';

    /**
     * Constructor
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        
        $this->auth->restrict($this->permissionView);
        $this->load->model('phone/phone_model');
        $this->load->model('buildings/buildings_model');
        $this->load->model('channel/channel_model');
        $this->lang->load('phone');
        
            $this->form_validation->set_error_delimiters("<span class='error'>", "</span>");
        
        Template::set_block('sub_nav', 'tgsz/_sub_nav');

        Assets::add_module_js('phone', 'phone.js');
        Assets::add_css(array('plugins/select2/select2.min.css', 'plugins/iCheck/all.css', 'plugins/datepicker/datepicker3.css'));
        Assets::add_js(array(Template::theme_url('plugins/select2/select2.full.min.js'), Template::theme_url('plugins/iCheck/icheck.min.js'), Template::theme_url('plugins/datepicker/bootstrap-datepicker.js')));
    }

    /**
     * Display a list of Phone data.
     *
     * @return void
     */
    public function index($offset = 0)
    {

        $where = "deleted = 0";
        
        // 搜索
        $getData = $this->input->get();
        $s = array();
        $channel_id = isset($getData['channels']) ? $getData['channels'] : '';
        if($channel_id) {
            $where .= " and channel_id  = $channel_id";
            $s['channels'] = $channel_id;
        }
        $building_id = isset($getData['buildings']) ? $getData['buildings'] : '';
        if ($building_id) {
            $where .= " and building_id  = $building_id";
            $s['buildings'] = $building_id;
        }  
        $q = trim($this->input->get('q'));
        if (!empty($q)){
            //判断是否是汉字
            if(preg_match("/[\x7f-\xff]/", $q)){
                $building = $this->buildings_model->like('name', $q)->find_by(array('deleted'=>0));
                $totalRows = $this->phone_model->where($where)->like('building_id', $building->id)->count_all();
                $records = $this->phone_model->where($where)->like('building_id', $building->id)->find_all();
            }else{
                $totalRows = $this->phone_model->where($where)->like('building_id', $q)->or_like('number', $q)->count_all();
                $records = $this->phone_model->where($where)->like('number', $q)->find_all();
            }
        }

        // Deleting anything?
        if (isset($_POST['delete'])) {
            $this->auth->restrict($this->permissionDelete);
            $checked = $this->input->post('checked');
            if (is_array($checked) && count($checked)) {

                // If any of the deletions fail, set the result to false, so
                // failure message is set if any of the attempts fail, not just
                // the last attempt

                $result = true;
                foreach ($checked as $pid) {
                    $deleted = $this->phone_model->delete($pid);
                    if ($deleted == false) {
                        $result = false;
                    }
                }
                if ($result) {
                    Template::set_message(count($checked) . ' ' . lang('phone_delete_success'), 'success');
                } else {
                    Template::set_message(lang('phone_delete_failure') . $this->phone_model->error, 'error');
                }
            }
        }
        
        // 搜索
        

        $pagerUriSegment = 5;
        $pagerBaseUrl = site_url(SITE_AREA . '/tgsz/phone/index') . '/';
        
        $limit  = 15;
        $totalRows = $this->phone_model->where($where)->count_all();
        $this->load->library('pagination');
        $this->pager['base_url']    = $pagerBaseUrl;
        $this->pager['total_rows']  = $totalRows;
        $this->pager['per_page']    = $limit;
        $this->pager['uri_segment'] = $pagerUriSegment;

        $channels = $this->channel_model->channels();

        $this->pagination->initialize($this->pager);
        $this->phone_model->where($where)->limit($limit, $offset);
        $order_array = array(
                'building_id'=>'DESC',
                'platform'=>'DESC',
                'id'=>'DESC',
            );
        $records = !empty($records) ? $records : $this->phone_model->where($where)->order_by($order_array)->find_all();
        if (!empty($records)) {
            $this->buildings_model->db->reset_query();
            foreach ($records as $key => $val) {
                $building = $this->buildings_model->getBuildingById($val->building_id);
                $records[$key]->building = $building;
                
                $records[$key]->platform_name = building_phone_platform()[$val->platform];
                foreach ($channels as $v) {
                    if ($val->channel_id == $v->id) {
                        $records[$key]->channel_name = $v->name;
                    }
                }
                
            }
        }

        // 楼盘
        $buildings = $this->buildings_model->order_by('id','desc')->buildings();
        //dump($buildings);exit;
        Template::set('buildings', $buildings);

        //获取所有渠道
        $channels = $this->channel_model->channels();
        Template::set('channels', $channels);

        Template::set('search', $s);

        Template::set('records', $records);
        
        Template::set('toolbar_title', lang('phone_manage'));

        Template::render();
    }
    
    /**
     * Create a Phone object.
     *
     * @return void
     */
    public function create()
    {
        $this->auth->restrict($this->permissionCreate);
        
        if (isset($_POST['save'])) {
            if ($insert_id = $this->save_phone()) {
                log_activity($this->auth->user_id(), lang('phone_act_create_record') . ': ' . $insert_id . ' : ' . $this->input->ip_address(), 'phone');
                Template::set_message(lang('phone_create_success'), 'success');

                redirect(SITE_AREA . '/tgsz/phone');
            }

            // Not validation error
            if ( ! empty($this->phone_model->error)) {
                Template::set_message(lang('phone_create_failure') . $this->phone_model->error, 'error');
            }
        }

        // 楼盘
        $buildings = $this->buildings_model->order_by('id','desc')->buildings();
        Template::set('buildings', $buildings);
        // 渠道
        $channels = $this->channel_model->channels();
        Template::set('channels', $channels);

        // $phone = new StdClass();
        // $phone->telephone = config_item('building.telephone');
        // Template::set('phone', $phone);
        
        Template::set('toolbar_title', lang('phone_action_create'));

        Template::render();
    }
    /**
     * Allows editing of Phone data.
     *
     * @return void
     */
    public function edit()
    {
        $id = $this->uri->segment(5);
        if (empty($id)) {
            Template::set_message(lang('phone_invalid_id'), 'error');

            redirect(SITE_AREA . '/tgsz/phone');
        }
        
        if (isset($_POST['save'])) {
            $this->auth->restrict($this->permissionEdit);

            if ($this->save_phone('update', $id)) {
                log_activity($this->auth->user_id(), lang('phone_act_edit_record') . ': ' . $id . ' : ' . $this->input->ip_address(), 'phone');
                Template::set_message(lang('phone_edit_success'), 'success');
                redirect(SITE_AREA . '/tgsz/phone');
            }

            // Not validation error
            if ( ! empty($this->phone_model->error)) {
                Template::set_message(lang('phone_edit_failure') . $this->phone_model->error, 'error');
            }
        }
        
        elseif (isset($_POST['delete'])) {
            $this->auth->restrict($this->permissionDelete);

            if ($this->phone_model->delete($id)) {
                log_activity($this->auth->user_id(), lang('phone_act_delete_record') . ': ' . $id . ' : ' . $this->input->ip_address(), 'phone');
                Template::set_message(lang('phone_delete_success'), 'success');

                redirect(SITE_AREA . '/tgsz/phone');
            }

            Template::set_message(lang('phone_delete_failure') . $this->phone_model->error, 'error');
        }
        
        Template::set('phone', $this->phone_model->find($id));

        // 楼盘
        $buildings = $this->buildings_model->buildings();
        Template::set('buildings', $buildings);
        // 渠道
        $channels = $this->channel_model->channels();
        Template::set('channels', $channels);

        Template::set('toolbar_title', lang('phone_edit_heading'));
        Template::render();
    }

    //--------------------------------------------------------------------------
    // !PRIVATE METHODS
    //--------------------------------------------------------------------------

    /**
     * Save the data.
     *
     * @param string $type Either 'insert' or 'update'.
     * @param int    $id   The ID of the record to update, ignored on inserts.
     *
     * @return boolean|integer An ID for successful inserts, true for successful
     * updates, else false.
     */
    private function save_phone($type = 'insert', $id = 0)
    {
        if ($type == 'update') {
            $_POST['id'] = $id;
        }

        // Validate the data
        $this->form_validation->set_rules($this->phone_model->get_validation_rules());
        if ($this->form_validation->run() === false) {
            return false;
        }

        // Make sure we only pass in the fields we want
        $post = $this->input->post();
        $data = $this->phone_model->prep_data($post);
        
        //dump($this->input->post());
        //给PC端每一个渠道分机号创建二维码(正式环境)
        if(ENVIRONMENT == 'production'){
            if($type == 'insert'){
                foreach ($data as $key => $value) {
                    if($value['platform'] == 1){
                        $channel_code = $this->channel_model->select("code")->find($value['channel_id']);
                        $this->createQrcode($value['building_id'],$value['platform'],$channel_code->code);
                    }
                    
                }
            }else if($type == 'update'){
                if($data['platform'] == 1){
                    $channel_code = $this->channel_model->select("code")->find($data['channel_id']);
                    $this->createQrcode($data['building_id'],$data['platform'],$channel_code->code);
                }

            }
        }


        // Additional handling for default values should be added below,
        // or in the model's prep_data() method
        
        $buildingId = $post['building_id'];
        $return = false;
        if ($type == 'insert') {
            // 分机号验证
            $ext = true;
            foreach ($data as $key => $val) {
                if (isset($val['number']) && $val['channel_id']>0) {
                    $number = $val['number'];
                    if ($this->phone_model->where("number = {$number} AND building_id != {$buildingId} AND deleted = 0")->count_all()) {
                        $this->phone_model->error = $number." 分机号已经存在";
                        $ext = false;
                        break;
                    }
                }
            }
            if (!$ext) return $ext;
            
            // $id = $this->phone_model->insert($data);
            $id = $this->phone_model->addPhones($buildingId, $data);

            if (is_numeric($id)) {
                $return = $id;
            }
        } elseif ($type == 'update') {
            // 分机号验证
            if (isset($data['number']) && $data['channel_id']>0) {
                $number = $data['number'];
                if ($this->phone_model->where("number = {$number} AND building_id != {$buildingId} AND deleted = 0 AND id != {$id}")->count_all()) {
                    $this->phone_model->error = $number." 分机号已经存在";
                    return false;
                }
            }
            $return = $this->phone_model->update($id, $data);
        }

        return $return;
    }

    public function photos() {
        $this->load->view('tgsz/index');
    }

    public function delete()
    {
        $id = $this->uri->segment(5);
        if (empty($id)) {
            Template::set_message(lang('phone_invalid_id'), 'error');

            redirect(SITE_AREA . '/tgsz/phone');
        }

        $this->auth->restrict($this->permissionDelete);

        if ($this->phone_model->delete($id)) {
            log_activity($this->auth->user_id(), lang('phone_act_delete_record') . ': ' . $id . ' : ' . $this->input->ip_address(), 'phone');
            Template::set_message(lang('phone_delete_success'), 'success');

            redirect(SITE_AREA . '/tgsz/phone');
        }

    }
    //创建二维码
    private function createQrcode($buildingId, $platform, $channel){
        
        $public = realpath(APPPATH .'../public');
        
        $url = site_url("buildings/front/buildinginfo/callext/".$buildingId."/".$platform."/".$channel);
        if($platform == 1){
            $platform_name = "pc";
        }else{
            $platform_name = "mobile";
        }
        //echo $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/qrcode/".$buildingId."/".$platform_name."/";exit();
        if(!is_dir($public."/qrcode/".$buildingId."/")){
            if(!is_dir($public."/qrcode/")){
                mkdir($public."/qrcode/");
            }
            mkdir($public."/qrcode/".$buildingId."/");
        }
        require_once APPPATH."third_party/phpqrcode/phpqrcode.php";     
        // 纠错级别：L、M、Q、H
        $errorCorrectionLevel = 'L'; 
        // 点的大小：1到10
        $matrixPointSize = 8;

        $nowpng = $public."/qrcode/".$buildingId."/".$platform_name."_".$channel.".png";
        QRcode::png($url, $nowpng, $errorCorrectionLevel, $matrixPointSize, 2);

        //上传到七牛
        require_once APPPATH.'third_party/Qiniu-7.0.7/autoload.php';

        $this->output->enable_profiler(false);

        // 公司账号
        $accessKey = config_item('qiniu.access_key');
        $secretKey = config_item('qiniu.secret_key');

        // 构建鉴权对象
        $auth = new Qiniu\Auth($accessKey, $secretKey);

        // 要上传的空间
        $bucket = config_item('qiniu.bucket');

        // 上传到七牛后保存的文件名
        $key = "qrcode/".$buildingId."/".$platform_name."_".$channel.".png";

        // 生成上传 Token
        $policy = array(
            'scope'=>$bucket.":".$key,
            'insertOnly'=> 0,
        );
        $token = $auth->uploadToken($bucket, $key, 3600, $policy);

        // 要上传文件的本地路径
        $filePath = $nowpng;

        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new Qiniu\Storage\UploadManager();

        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        // echo "\n====> putFile result: \n";
        // if ($err !== null) {
        //     var_dump($err);
        // } else {
        //     var_dump($ret);
        // }
    }

}